package com.netease.task.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    // 1、创建realm对象
    @Bean(name="userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }


    // 2、DefaultWebSecurityManager
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    // 3、ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();

        // 设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        Map<String,String> filterMap = new LinkedHashMap<>();

        // 授权
        filterMap.put("/api/public","perms[seller:qx]");
        filterMap.put("/api/publicSubmit","perms[seller:qx]");
        filterMap.put("/api/edit","perms[seller:qx]");
        filterMap.put("/api/editSubmit","perms[seller:qx]");
        filterMap.put("/api/delete","perms[seller:qx]");
        filterMap.put("/api/sellerindex","perms[seller:qx]");

        filterMap.put("/api/noSell","perms[buyer:qx]");
        filterMap.put("/api/buy","perms[buyer:qx]");
        filterMap.put("/api/confirmBuy","perms[buyer:qx]");
        filterMap.put("/api/buyerindex","perms[buyer:qx]");
        filterMap.put("/api/toAccount","perms[buyer:qx]");
        filterMap.put("/api/toSettleAccount","perms[buyer:qx]");

        // 拦截
        filterMap.put("/api/show","anon");  // /api/show无需过滤
        filterMap.put("/api/*","authc");  // api下的页面必须认证才能访问

        bean.setFilterChainDefinitionMap(filterMap);
        // 设置登录请求
        bean.setLoginUrl("/toLogin");
        // 未授权的请求转到到/noauthc页面
        bean.setUnauthorizedUrl("/noauthc");

        return bean;
    }

}
